package com.kfm.jdbc.day0405;

/**
 * 创建三个线程，分别打印A、B、C，要求这三个线程一起运行，打印 n 次，输出形如“AAABBBCCC....”的字符串。
 */
public class PrintThread implements Runnable {
    private static final Object lock = new Object();
    private static int currentLetter = 0;
    private static final int n = 5;

    private char letter;
    private int order;

    public PrintThread(char letter, int order) {
        this.letter = letter;
        this.order = order;
    }

    public void run() {
        for (int i = 0; i < n; i++) {
            synchronized (lock) {
                while (letter != currentLetter + 'A') {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(letter);
                currentLetter = (currentLetter + 1) % 3;
                lock.notifyAll();
            }
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new PrintThread('A', 0));
        Thread t2 = new Thread(new PrintThread('B', 1));
        Thread t3 = new Thread(new PrintThread('C', 2));

        t1.start();
        t2.start();
        t3.start();

        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println();
    }
}
